#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__
#include "Message.hpp"
#include "Socket.hpp"
#include "SocketIO.hpp"
#include "InetAddress.hpp"
#include <functional>
#include <memory>
using std::shared_ptr;
using std::function;

namespace wd{

class EventLoop;
class TcpConnection;
using TcpConnectionPtr = shared_ptr<TcpConnection>;  //为什么用智能指针，而且是shared_ptr 
using TcpConnectionCallback = function<void(TcpConnectionPtr)>; 

class TcpConnection
:public std::enable_shared_from_this<TcpConnection>
{

public:
    TcpConnection(int netfd, EventLoop *);
    void send(const string&);
    string receive();
    int readPacket(Packet&); //接受数据包

    string toString();
    void shutdowd();

    bool isClosed();
    void setAllCallbacks(const TcpConnectionCallback & cb1, 
                         const TcpConnectionCallback & cb2,
                         const TcpConnectionCallback & cb3)
    {
        _onConnection = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }


    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();
    void sendInLoop(const string &msg);
    void sendInLoop(const TLV&); //发送TLV格式消息

    
    //添加和获取连接用户的名字

    void setUsername(const string& ctx){ _username = ctx ;}
    string getUsername()const {return _username;}

private:
    InetAddress getLocalAddress();
    InetAddress getPeerAddress();


private:
    Socket      _sock;
    InetAddress _localAddr;
    InetAddress _peerAddr;
    SocketIO    _sockIO;
    TcpConnectionCallback _onConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
    EventLoop            *_loop;

    //添加连接的用户名
    string _username;


};







} // end of namespace wd

#endif

